import 'package:family_expense/features/account_user/services/user_service.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class ResetLoginPassword extends StatefulWidget {
  const ResetLoginPassword({super.key});

  @override
  State<ResetLoginPassword> createState() => _ResetLoginPasswordState();
}

class _ResetLoginPasswordState extends State<ResetLoginPassword> {
  final TextEditingController _passwordController = TextEditingController();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final UserService _userService = UserService();

  late String _currentPassword;
  late String _newPassword;

  @override
  void dispose() {
    _passwordController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: _buildAppBar(), body: _buildForm());
  }

  /// Builds app bar.
  PreferredSizeWidget _buildAppBar() {
    return AppBar(title: const Text('修改密码'));
  }

  /// Builds the input form.
  Widget _buildForm() {
    // DO NOT PUT [Form] in [ListView]. Uses [SingleChildScrollView] instead.
    // Textfield in gallery gets reset if scrolled out of view.
    // https://github.com/flutter/flutter/issues/11500
    return Form(
      key: _formKey,
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            TextFormField(
              keyboardType: TextInputType.text,
              obscureText: true,
              decoration: const InputDecoration(hintText: '请输入现有密码'),
              validator: (value) => FormTextFieldValidator(
                '现有密码',
                value,
                minLength: User.passwordMinLength,
                maxLength: User.passwordMaxLength,
              ).validate(),
              onSaved: (value) => _currentPassword = value!,
            ),
            const SizedBox(height: 20.0),
            TextFormField(
              controller: _passwordController,
              keyboardType: TextInputType.text,
              obscureText: true,
              decoration: const InputDecoration(
                hintText: '请输入新密码（长度至少${User.passwordMinLength}位）',
              ),
              validator: (value) => FormTextFieldValidator(
                '新密码',
                value,
                minLength: User.passwordMinLength,
                maxLength: User.passwordMaxLength,
              ).validate(),
              onSaved: (value) => _newPassword = value!,
            ),
            const SizedBox(height: 20.0),
            TextFormField(
              keyboardType: TextInputType.text,
              obscureText: true,
              decoration: const InputDecoration(hintText: '请再次输入新密码'),
              validator: (value) => FormTextFieldValidator(
                '确认新密码',
                value,
                label2: '新密码',
                value2: _passwordController.text,
              ).validate(),
            ),
            const SizedBox(height: 60.0),
            Container(
              padding: const EdgeInsets.only(top: 20.0),
              height: 60.0,
              child: PressStatusButton(
                onPressed: _save,
                disabledChild: const Text(
                  '正在保存',
                  style: TextStyle(fontSize: 20.0),
                ),
                child: const Text('保 存', style: TextStyle(fontSize: 20.0)),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Saves current input data.
  Future<void> _save() async {
    // Validate returns true if the form is valid, or false otherwise.
    if (!_formKey.currentState!.validate()) {
      showToast('请正确填写各项信息');
      return;
    }

    // Saves current form.
    _formKey.currentState!.save();

    // If user is updating own password then need to validate the current password.
    final success = await _userService.updateCurrentUserPassword(
      _currentPassword,
      _newPassword,
    );

    if (success) {
      showToast('密码修改成功');

      // DO NOT use BuildContext across asynchronous gaps.
      // https://dart-lang.github.io/linter/lints/use_build_context_synchronously.html
      if (mounted) {
        NavigatorHelper.pop(context);
      }
    } else {
      showToast('现有密码验证失败，请重新输入。');
    }
  }
}
